//
//  SegmentControl.m
//  GameSearch
//
//  Created by MacBook Pro on 15-4-30.
//  Copyright (c) 2015年 JunHaoBsBs. All rights reserved.
//

#import "SegmentControl.h"
#import "UIButton+Position.h"

@interface SegmentControl()

@property (nonatomic,assign) NSInteger currSelectIndex;//当前点击
@property (nonatomic,strong) NSArray *selectImgs;
@property (nonatomic,strong) NSArray *uselectImgs;
@property (nonatomic,strong) NSMutableArray <UIButton *>*btnArray;
@property (nonatomic, strong) NSArray<UILabel *> *badgeViews;

@end

static NSUInteger const XJHSegmentControlTag = 16789;
@implementation SegmentControl

-(id)initWithTitles:(NSArray*)titles frame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    self.titles = titles;
    if(self)
    {
        self.selectIndex = 0;
        self.currSelectIndex = 0;
        self.clipsToBounds = YES;
        self.backgroundColor = [UIColor whiteColor];
        [self setup];
    }
    return self;
}

-(id)initWithTitles:(NSArray*)titles frame:(CGRect)frame images:(NSArray *)images selImages:(NSArray *)selImages{
    
    self = [super initWithFrame:frame];
    self.titles = titles;
    if(self)
    {
        self.selectIndex = 0;
        self.currSelectIndex = 0;
        self.uselectImgs = images;
        self.selectImgs = selImages;
        self.clipsToBounds = YES;
        self.backgroundColor = [UIColor whiteColor];
        [self setup];
    }
    return self;
}

-(void)setup
{
    [self addLine];
    NSInteger itemCount = self.titles.count;
    int buttonWidth = CGRectGetWidth(self.frame)/itemCount;
    
    self.lineV.frame = CGRectMake(0, CGRectGetHeight(self.frame)-2, buttonWidth, 2);
    self.btnArray = [NSMutableArray array];
    NSMutableArray *badgeViews = [NSMutableArray array];
    for(int i=0;i<itemCount;i++){
        
        UIButton* button = [[UIButton alloc]initWithFrame:CGRectMake(i*buttonWidth, 0, buttonWidth, CGRectGetHeight(self.frame))];
        [button setTitle:[self.titles objectAtIndex:i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        if (self.uselectImgs.count == itemCount && self.selectImgs.count == itemCount) {
            [button setImage:[self.uselectImgs objectAtIndex:i] forState:UIControlStateNormal];
            [button setImage:[self.selectImgs objectAtIndex:i] forState:UIControlStateSelected];
        }
        [button setTitleColor:[UIColor colorWithRed:129/255.0 green:129/255.0 blue:129/255.0 alpha:1.0]
          forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRed:255/255.0 green:153/255.0 blue:0/255.0 alpha:1.0] forState:UIControlStateSelected];
        button.adjustsImageWhenHighlighted = NO;
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = XJHSegmentControlTag+i;
        [self addSubview:button];
        [self.btnArray addObject:button];
        if(i == 0){
            button.selected = YES;
        }
        
        UILabel *badgeView = [[UILabel alloc] initWithFrame:CGRectMake(button.bounds.size.width - 30, 0, 30, 15)];
        badgeView.layer.masksToBounds = YES;
        badgeView.backgroundColor = [UIColor redColor];
        badgeView.textAlignment = NSTextAlignmentCenter;
        badgeView.textColor = [UIColor whiteColor];
        badgeView.font = [UIFont systemFontOfSize:12];
        badgeView.hidden = YES;
        [button addSubview:badgeView];
        [badgeViews addObject:badgeView];
    }
    self.badgeViews = badgeViews.copy;
    
    for(int i=0;i<_titles.count-1;i++){
        
        UIView *grayView = [[UIView alloc]initWithFrame:CGRectMake((i+1)*buttonWidth-1, 0, 1, CGRectGetHeight(self.frame))];
        grayView.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0];
        [self addSubview:grayView];
    }
}

- (void)shouldShowBadgeViews:(BOOL)show{
    for (UILabel *lb in self.badgeViews) {
        lb.hidden = !show;
    }
}

- (void)setBadgeTitle:(NSArray *)titles{
    if (titles.count != self.badgeViews.count) {
        [self shouldShowBadgeViews:NO];
        return;
    }
    
    for (int i = 0; i < titles.count; i++) {
        NSString *num = titles[i];
        UILabel *lb = self.badgeViews[i];
        if (num.length <= 0 || [num  isEqual: @"0"]) {
            lb.hidden = YES;
            continue;
        }
        lb.hidden = NO;
        lb.text = [NSString stringWithFormat:@"%@",num];
        
        // 计算尺寸
        NSDictionary *attrs = @{NSFontAttributeName:lb.font};
        CGSize size = [lb.text sizeWithAttributes:attrs];
        
        size.width += 7;
        if (size.width < size.height) {
            size.width = size.height;
        }
        
        lb.bounds = CGRectMake(0, 0, size.width, size.height);
        lb.layer.cornerRadius = size.height * 0.5;
        
    }
}

-(void)setImagePosition:(NSInteger)position spacing:(CGFloat) space {

    for (UIButton *btn in self.btnArray) {
        [btn positionButtonImageAtPosition:position withSpacing:space];
    }
    
}


-(void)resetSelectIndex:(NSInteger)selectIndex {
    if (selectIndex == _currSelectIndex) {
        return;
    }
    
    for (UIButton *btn in self.btnArray) {
        NSInteger index = btn.tag-XJHSegmentControlTag;
        if (selectIndex == index) {
            
            btn.selected = YES;
            UIButton *lastBtn = (UIButton *)[self viewWithTag:(XJHSegmentControlTag + _currSelectIndex)];
            if(lastBtn == btn){
                [lastBtn setSelected:YES];
            }else{
                [lastBtn setSelected:NO];
            }
            
            _currSelectIndex = index;
            
            [UIView animateWithDuration:0.2 animations:^{
                self.lineV.frame = CGRectMake(btn.frame.origin.x, CGRectGetHeight(self.frame)-2,  CGRectGetWidth(self.frame)/self.titles.count, 2);
            } completion:^(BOOL finished) {
                
            }];
            
        }
    }
}

-(void)click:(UIButton*)button
{

    NSInteger index = button.tag-XJHSegmentControlTag;
    if (index == _currSelectIndex) {
        return;
    }
    button.selected = YES;
    UIButton *lastBtn = (UIButton *)[self viewWithTag:(XJHSegmentControlTag+_currSelectIndex)];
    if(lastBtn == button){
        [lastBtn setSelected:YES];
    }else{
        [lastBtn setSelected:NO];
    }
    _currSelectIndex = index;
    
    [UIView animateWithDuration:0.2 animations:^{
        self.lineV.frame = CGRectMake(button.frame.origin.x, CGRectGetHeight(self.frame)-2,  CGRectGetWidth(self.frame)/self.titles.count, 2);
    } completion:^(BOOL finished) {
        if(self.eventBlock){
            self.eventBlock(index);
        }
    }];
}
- (NSInteger)selectIndex{
    return _currSelectIndex;
}

-(void)addLine
{
    self.lineV = [[UIView alloc]init];
    self.lineV.backgroundColor = [UIColor colorWithRed:255/255.0 green:153/255.0 blue:0/255.0 alpha:1.0];
    [self addSubview:self.lineV];
}

@end
